<template>
  <div class="dashboard-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="dashboard-cards">
      <el-col :xs="24" :sm="12" :lg="6" v-for="item in statCards" :key="item.title">
        <el-card class="stat-card" :body-style="{ padding: '20px' }">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: item.color }">
              <el-icon :size="24" color="white">
                <component :is="item.icon" />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">{{ item.title }}</div>
              <div class="stat-value">{{ item.value }}</div>
              <div class="stat-trend" :class="item.trend > 0 ? 'up' : 'down'">
                <el-icon :size="12">
                  <CaretTop v-if="item.trend > 0" />
                  <CaretBottom v-else />
                </el-icon>
                {{ Math.abs(item.trend) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="dashboard-charts">
      <!-- 销售趋势图 -->
      <el-col :xs="24" :lg="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>销售趋势</span>
              <el-date-picker
                v-model="salesDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="small"
                style="width: 240px"
                @change="refreshSalesChart"
              />
            </div>
          </template>
          <div ref="salesChart" class="chart-container" style="height: 400px"></div>
        </el-card>
      </el-col>

      <!-- 商品分类占比 -->
      <el-col :xs="24" :lg="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>商品分类占比</span>
            </div>
          </template>
          <div ref="categoryChart" class="chart-container" style="height: 400px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单和库存预警 -->
    <el-row :gutter="20" class="dashboard-tables">
      <el-col :xs="24" :lg="12">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>最新订单</span>
              <el-button type="primary" link @click="$router.push('/orders')">
                查看全部
              </el-button>
            </div>
          </template>
          <el-table :data="latestOrders" style="width: 100%" size="small">
            <el-table-column prop="orderNo" label="订单号" width="120" />
            <el-table-column prop="customer" label="客户" />
            <el-table-column prop="amount" label="金额" width="80" />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="getOrderStatusType(row.status)" size="small">
                  {{ getOrderStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="12">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>库存预警</span>
              <el-button type="primary" link @click="$router.push('/inventory')">
                查看全部
              </el-button>
            </div>
          </template>
          <el-table :data="lowStockProducts" style="width: 100%" size="small">
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="stock" label="当前库存" width="100" />
            <el-table-column prop="threshold" label="预警值" width="100" />
            <el-table-column label="操作" width="80">
              <template #default>
                <el-button type="primary" link size="small">补货</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快捷操作 -->
    <el-row :gutter="20" class="dashboard-actions">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>快捷操作</span>
          </template>
          <div class="quick-actions">
            <el-button
              v-for="action in quickActions"
              :key="action.name"
              :type="action.type"
              :icon="action.icon"
              @click="$router.push(action.path)"
            >
              {{ action.name }}
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'

// 统计数据
const statCards = ref([
  {
    title: '今日销售额',
    value: '¥12,345',
    icon: 'Money',
    color: '#5470c6',
    trend: 12.5
  },
  {
    title: '今日订单数',
    value: '156',
    icon: 'Document',
    color: '#91cc75',
    trend: 8.3
  },
  {
    title: '会员总数',
    value: '2,345',
    icon: 'User',
    color: '#fac858',
    trend: 5.2
  },
  {
    title: '商品总数',
    value: '1,234',
    icon: 'Goods',
    color: '#ee6666',
    trend: -2.1
  }
])

// 图表实例
let salesChartInstance: ECharts | null = null
let categoryChartInstance: ECharts | null = null

const salesChart = ref<HTMLElement>()
const categoryChart = ref<HTMLElement>()
const salesDateRange = ref<Date[]>([])

// 模拟数据
const latestOrders = ref([
  { orderNo: '20240101001', customer: '张三', amount: 299, status: 1 },
  { orderNo: '20240101002', customer: '李四', amount: 599, status: 2 },
  { orderNo: '20240101003', customer: '王五', amount: 199, status: 3 },
  { orderNo: '20240101004', customer: '赵六', amount: 899, status: 1 },
  { orderNo: '20240101005', customer: '钱七', amount: 399, status: 4 }
])

const lowStockProducts = ref([
  { name: 'iPhone 15 Pro', stock: 5, threshold: 10 },
  { name: 'MacBook Air M2', stock: 3, threshold: 5 },
  { name: 'AirPods Pro', stock: 8, threshold: 15 },
  { name: 'iPad Pro', stock: 2, threshold: 8 }
])

const quickActions = ref([
  { name: '新增商品', type: 'primary', icon: 'Plus', path: '/products/add' },
  { name: '创建订单', type: 'success', icon: 'DocumentAdd', path: '/orders/create' },
  { name: '添加会员', type: 'warning', icon: 'User', path: '/members/add' },
  { name: '创建优惠券', type: 'danger', icon: 'Ticket', path: '/marketing/coupons/add' }
])

// 获取订单状态
const getOrderStatusType = (status: number) => {
  const types = ['', 'primary', 'success', 'warning', 'danger', 'info']
  return types[status] || 'info'
}

const getOrderStatusText = (status: number) => {
  const texts = ['', '待付款', '待发货', '待收货', '已完成', '已取消']
  return texts[status] || '未知'
}

// 初始化销售趋势图
const initSalesChart = () => {
  if (!salesChart.value) return
  
  salesChartInstance = echarts.init(salesChart.value)
  
  const option = {
    title: {
      text: '销售趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['销售额', '订单数'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额',
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      {
        type: 'value',
        name: '订单数',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        smooth: true,
        data: [1200, 1900, 900, 2300, 2900, 3300, 3100],
        itemStyle: {
          color: '#5470c6'
        }
      },
      {
        name: '订单数',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: [20, 32, 18, 45, 58, 66, 62],
        itemStyle: {
          color: '#91cc75'
        }
      }
    ]
  }
  
  salesChartInstance.setOption(option)
}

// 初始化商品分类图
const initCategoryChart = () => {
  if (!categoryChart.value) return
  
  categoryChartInstance = echarts.init(categoryChart.value)
  
  const option = {
    title: {
      text: '商品分类占比',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['手机', '电脑', '配件', '家电', '其他']
    },
    series: [
      {
        name: '商品分类',
        type: 'pie',
        radius: '50%',
        center: ['50%', '60%'],
        data: [
          { value: 335, name: '手机' },
          { value: 310, name: '电脑' },
          { value: 234, name: '配件' },
          { value: 135, name: '家电' },
          { value: 148, name: '其他' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  categoryChartInstance.setOption(option)
}

// 刷新销售图表
const refreshSalesChart = () => {
  console.log('刷新销售图表', salesDateRange.value)
}

// 窗口大小改变时重新调整图表
const handleResize = () => {
  salesChartInstance?.resize()
  categoryChartInstance?.resize()
}

onMounted(() => {
  initSalesChart()
  initCategoryChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  salesChartInstance?.dispose()
  categoryChartInstance?.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
}

.dashboard-cards {
  margin-bottom: 20px;
  
  .stat-card {
    margin-bottom: 20px;
    
    .stat-content {
      display: flex;
      align-items: center;
      
      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
      }
      
      .stat-info {
        flex: 1;
        
        .stat-title {
          font-size: 14px;
          color: #666;
          margin-bottom: 5px;
        }
        
        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #333;
          margin-bottom: 5px;
        }
        
        .stat-trend {
          font-size: 12px;
          
          &.up {
            color: #67c23a;
          }
          
          &.down {
            color: #f56c6c;
          }
        }
      }
    }
  }
}

.dashboard-charts {
  margin-bottom: 20px;
  
  .chart-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .chart-container {
      width: 100%;
    }
  }
}

.dashboard-tables {
  margin-bottom: 20px;
  
  .table-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}

.dashboard-actions {
  .quick-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }
}

@media screen and (max-width: 768px) {
  .dashboard-cards {
    .stat-card {
      margin-bottom: 10px;
    }
  }
}
</style>
